import 'package:cher_flare/common/models/ly_user_works_model.dart';
import 'package:cher_flare/config/url_api.dart';
import 'package:cher_flare/http/http_utils.dart';
import 'package:cher_flare/modules/discovery/ly_discovery_card_item.dart';
import 'package:cher_flare/routes/app_pages.dart';
import 'package:cher_flare/utils/ly_data_manager.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';

import '../../common/models/ly_broadcaster_model.dart';
import '../../common/widgets/ly_action_sheet_page.dart';
import '../../utils/app_color.dart';
import 'controllers/ly_works_list_controller.dart';

class LYDiscoveryPage extends StatefulWidget {
  const LYDiscoveryPage({super.key});

  @override
  State<LYDiscoveryPage> createState() => _LYDiscoveryPageState();
}

class _LYDiscoveryPageState extends State<LYDiscoveryPage> {
  final controller = Get.put(LYWorksListController());

  void _naviAddButtonDidClick() async {
    Get.toNamed(AppPages.publishWorks, arguments: {'source': 'discovery'})
        ?.then((value) {
      controller.refreshWorksData();
    });
  }

  void _avatarOnTap(LYWorksModel model) {
    Get.toNamed(AppPages.userPage, arguments: {
      'userId': model.userId,
      'nickname': model.nickname,
      'avatar': model.avatar
    });
  }

  void _worksDidClick(LYWorksModel model) {
    Get.toNamed(AppPages.worksDetailPage, arguments: {'works': model})
        ?.then((value) {
      controller.refreshWorksData();
    });
  }

  void _greatDidClick(LYWorksModel model) {
    model.isGreat = !(model.isGreat ?? false);
    LYDataManager.share.updateLocalWorksData();
    setState(() {});
  }

  void _moreButtonDidClick(int index) async {
    final model = controller.worksList[index];
    LyBroadcasterModel? userModel =
        await LYDataManager.share.searchUser(model.userId ?? '');
    debugPrint(
        '============${model.userId}=========${userModel?.userId}====${userModel?.isFriend}');
    final title = userModel?.isFriend == true ? "Unfollow" : "Follow";
    final sheet = LYActionSheetPage(
      titles: [title, 'Block', 'Report'],
      onTap: (type) {
        if (type == 0) {
          _followDidClick(userModel);
        } else if (type == 1) {
          _blockDidClick(model);
        } else if (type == 2) {
          _reportDidClick(index);
        }
      },
    );
    Get.dialog(sheet, useSafeArea: false);
  }

  void _followDidClick(LyBroadcasterModel? userModel) async {
    EasyLoading.show();
    if (userModel?.isFriend == true) {
      final response = await HttpUtils.getInstance
          .post(URLApi.unfriend, data: {'followUserId': userModel?.userId});
      userModel?.isFriend = false;
      EasyLoading.showToast('Unfollow successfully');
    } else {
      final response = await HttpUtils.getInstance
          .post(URLApi.addFriend, data: {'followUserId': userModel?.userId});
      userModel?.isFriend = true;
      EasyLoading.showToast('Follow successfully.');
    }
    LYDataManager.share.updateUserInfo();
    EasyLoading.dismiss();
  }

  void _blockDidClick(LYWorksModel model) async {
    EasyLoading.show();
    await LYDataManager.share.blackUser(model.userId);
    controller.worksList = LYDataManager.share.allUserWorks
        .where((element) => element.isBlack != true)
        .toList();
    EasyLoading.dismiss();
    EasyLoading.showToast("Blocked successfully");
    setState(() {});
  }

  void _reportDidClick(int index) {
    final titles = [
      'Pornographic',
      'False gender',
      'Fraud',
      'Political sensitive',
      'Other'
    ];
    final sheet = LYActionSheetPage(
      titles: titles,
      onTap: (index) {
        final model = controller.worksList[index];
        _submitReport(titles[index], "Report", model.userId).then((value) {
          EasyLoading.showToast('Report Successfully');
        });
      },
    );
    Get.dialog(sheet, useSafeArea: false);
  }

  Future<void> _submitReport(String complainSub, String complainCategory,
      String? broadcasterId) async {
    EasyLoading.show();
    Map<String, String> parameters = {
      'broadcasterId': broadcasterId ?? '',
      'complainSub': complainSub,
      'complainCategory': complainCategory
    };
    final response = await HttpUtils.getInstance
        .post(URLApi.insertBlockRecord, data: parameters);
    EasyLoading.dismiss();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          "Discovery",
          style: TextStyle(fontSize: 24, color: AppColors.color202020),
        ),
        backgroundColor: AppColors.colorD7FFDF,
        elevation: 0,
        centerTitle: false,
        flexibleSpace: FlexibleSpaceBar(
          background: Image.asset(
            //或者Image.network
            'assets/images/navi_bg.png',
            fit: BoxFit.fill,
          ),
        ),
        actions: [
          InkWell(
            onTap: () => _naviAddButtonDidClick(),
            child: Container(
              padding: const EdgeInsets.only(right: 15),
              child: Image.asset(
                'assets/images/navi_add.png',
                width: 30,
                height: 30,
              ),
            ),
          )
        ],
      ),
      backgroundColor: AppColors.colorEEFCFD,
      body: GetBuilder(
          init: controller,
          id: 'list',
          builder: (_) {
            return ListView.separated(
              padding: const EdgeInsets.all(16),
              itemBuilder: (ctx, index) {
                final model = controller.worksList[index];
                return LYDiscoveryCardItem(
                  image: model.cover,
                  title: model.title,
                  content: model.description,
                  avatar: model.avatar,
                  nickName: model.nickname,
                  isGreat: model.isGreat ?? false,
                  isSave: model.isSave,
                  onTap: () {
                    _worksDidClick(model);
                  },
                  avatarOnTap: () => _avatarOnTap(model),
                  greatOnTap: () => _greatDidClick(model),
                  topIconOnTap: model.isSave == true
                      ? null
                      : () => _moreButtonDidClick(index),
                );
              },
              separatorBuilder: (ctx, index) {
                return const SizedBox(
                  height: 16,
                );
              },
              itemCount: controller.worksList.length,
              cacheExtent: 320,
            );
          }),
    );
  }
}
